package com.java110.mall.system.importData.adapt;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.data.ImportProduct;
import com.java110.dto.data.ImportProductExtand;
import com.java110.dto.housekeeping.HousekeepingServDto;
import com.java110.dto.inoutOrder.InoutOrderDto;
import com.java110.dto.log.AssetImportLogDetailDto;
import com.java110.dto.product.ProductCategoryDto;
import com.java110.dto.product.ProductSpecDto;
import com.java110.dto.shop.ShopHouseDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.cart.IInoutOrderInnerServiceSMO;
import com.java110.intf.cart.IInoutOrderProductInnerServiceSMO;
import com.java110.intf.goods.*;
import com.java110.intf.shop.IShopHouseInnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.mall.system.importData.DefaultImportData;
import com.java110.mall.system.importData.IImportDataAdapt;
import com.java110.po.inoutOrder.InoutOrderPo;
import com.java110.po.inoutOrder.InoutOrderProductPo;
import com.java110.po.product.ProductPo;
import com.java110.po.product.ProductServKeywordPo;
import com.java110.po.product.ProductSpecValuePo;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 房产信息导入 适配器
 * 前端请求 时 必须传入
 * param.append('importAdapt', "importRoomOwner");
 */
@Service("importProductQueueData")
public class ImportProductQueueDataAdapt extends DefaultImportData implements IImportDataAdapt {

    @Autowired
    private IProductCategoryInnerServiceSMO productCategoryInnerServiceSMOImpl;

    @Autowired
    private IShopHouseInnerServiceSMO shopHouseInnerServiceSMOImpl;

    @Autowired
    private IProductInnerServiceSMO productInnerServiceSMOImpl;

    @Autowired
    private IProductSpecValueInnerServiceSMO productSpecValueInnerServiceSMOImpl;

    @Autowired
    private IProductDetailInnerServiceSMO productDetailInnerServiceSMOImpl;

    @Autowired
    private IProductServKeywordInnerServiceSMO productServKeywordInnerServiceSMOImpl;

    @Autowired
    private IInoutOrderProductInnerServiceSMO iInoutOrderProductInnerServiceSMOImpl;

    @Autowired
    private IInoutOrderInnerServiceSMO inoutOrderInnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userInnerServiceSMOImpl;


    @Autowired
    private IProductSpecInnerServiceSMO productSpecValuePosImpl;
    @Autowired
    private IShopDistributionModeInnerServiceSMO shopDistributionModeInnerServiceSMOImpl;

    @Override
    public void importData(List<AssetImportLogDetailDto> assetImportLogDetailDtos) {
        importDatas(assetImportLogDetailDtos);
    }

    private void importDatas(List<AssetImportLogDetailDto> infos) {
        String state = "";
        String msg = "";
        for (AssetImportLogDetailDto assetImportLogDetailDto : infos) {

            try {
                doImportData(assetImportLogDetailDto);
                updateImportLogDetailState(assetImportLogDetailDto.getDetailId());
            } catch (Exception e) {
                e.printStackTrace();
                updateImportLogDetailState(assetImportLogDetailDto.getDetailId(), e);
            }
        }

    }

    /**
     * 导入数据
     *
     * @param assetImportLogDetailDto
     */
    private void doImportData(AssetImportLogDetailDto assetImportLogDetailDto) {
        JSONObject data = JSONObject.parseObject(assetImportLogDetailDto.getContent());
        ImportProduct importProduct = BeanConvertUtil.covertBean(data, ImportProduct.class);
        List<ImportProductExtand> importProductExtands
                = BeanConvertUtil.covertBeanList(data.getJSONArray("importProductExtands"), ImportProductExtand.class);
        importProduct.setImportProductExtands(importProductExtands);


        ProductCategoryDto productCategoryDto = new ProductCategoryDto();
        productCategoryDto.setShopId(importProduct.getShopId());
        productCategoryDto.setCategoryName(importProduct.getCategoryName());
        List<ProductCategoryDto> productCategoryDtos = productCategoryInnerServiceSMOImpl.queryProductCategorys(productCategoryDto);

        Assert.listOnlyOne(productCategoryDtos, "目录不存在");

        ShopHouseDto shopHouseDto = new ShopHouseDto();
        shopHouseDto.setShopId(importProduct.getShopId());
        shopHouseDto.setShName(importProduct.getShName());
        List<ShopHouseDto> shopHouseDtos = shopHouseInnerServiceSMOImpl.queryShopHouses(shopHouseDto);
        Assert.listOnlyOne(shopHouseDtos, "仓库不存在");

        ProductPo productPo = new ProductPo();
        productPo.setProductId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_productId));
        productPo.setBarCode("1");
        productPo.setCategoryId(productCategoryDtos.get(0).getCategoryId());
        productPo.setKeyword(importProduct.getKeyword());
        productPo.setIsPostage("2");
        productPo.setProdDesc("系统导入");
        productPo.setProdName(importProduct.getProdName());
        productPo.setShId(shopHouseDtos.get(0).getShId());
        productPo.setShName(shopHouseDtos.get(0).getShName());
        productPo.setSort(importProduct.getProductId());
        productPo.setShopId(importProduct.getShopId());
        productPo.setState("上架".equals(importProduct.getStateName()) ? "2002" : "1001");
        productPo.setStoreId(importProduct.getStoreId());
        productPo.setUnitName(importProduct.getUnitName());
        productPo.setWarnStock(importProduct.getWarnStock());
        int flag = productInnerServiceSMOImpl.saveProduct(productPo);
        //关键词处理
        doSavakeywords(productPo);
        if (flag < 1) {
            throw new IllegalArgumentException("保存失败");
        }

        ProductSpecValuePo productSpecValuePo = null;
        List<ProductSpecValuePo> productSpecValuePos = new ArrayList<>();
        String isDefault = "T";
        for (ImportProductExtand importProductExtand : importProductExtands) {
            productSpecValuePo = new ProductSpecValuePo();
            productSpecValuePo.setWillExpire("0");
            productSpecValuePo.setAttrition("0");
            productSpecValuePo.setValueId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_valueId));
            productSpecValuePo.setProductId(productPo.getProductId());
            productSpecValuePo.setStock(importProductExtand.getStock());
            productSpecValuePo.setSales(importProductExtand.getSales());
            productSpecValuePo.setShopId(importProduct.getShopId());
            productSpecValuePo.setStoreId(importProduct.getStoreId());
            productSpecValuePo.setBarCode(importProductExtand.getBarCode());

            productSpecValuePo.setCostPrice(importProductExtand.getCostPrice());
            productSpecValuePo.setIsDefault(isDefault);
            productSpecValuePo.setMinusStock("1");
            productSpecValuePo.setOtPrice(importProductExtand.getOtPrice());
            productSpecValuePo.setPrice(importProductExtand.getPrice());
            productSpecValuePo.setVipPrice(importProductExtand.getVipPrice());
            productSpecValuePo.setSpecId("-1");
            productSpecValuePo.setSpecName(importProductExtand.getSpecName());
            productSpecValuePo.setOwnerPrice(importProductExtand.getVipPrice());
            flag = productSpecValueInnerServiceSMOImpl.saveProductSpecValue(productSpecValuePo);
            if (flag < 1) {
                throw new IllegalArgumentException("保存规格失败");
            }
            isDefault = "F";

            productSpecValuePos.add(productSpecValuePo);
        }

        InoutOrderPo inoutOrderPo = new InoutOrderPo();
        inoutOrderPo.setOrderId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_orderId));
        inoutOrderPo.setShopId(productPo.getShopId());
        inoutOrderPo.setState(InoutOrderDto.STATE_C);
        inoutOrderPo.setOrderType(InoutOrderDto.ORDER_TYPE_IN);
        inoutOrderPo.setPersonId(importProduct.getUserId());
        UserDto userDto = new UserDto();
        userDto.setUserId(importProduct.getUserId());
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "未包含用户信息");
        inoutOrderPo.setPersonName(userDtos.get(0).getName());
        inoutOrderPo.setRemark("添加商品初始化入库");
        //开始保存 inoutOrderProduct
        InoutOrderProductPo inoutOrderProductPo = null;
        List<InoutOrderProductPo> inoutOrderProductPos = new ArrayList<>();

        for (ProductSpecValuePo tmpProductSpecValuePo : productSpecValuePos) {
            if (productSpecValuePo.getStock() != null && Integer.parseInt(tmpProductSpecValuePo.getStock()) > 0) {//初始库存大于0
                inoutOrderProductPo = new InoutOrderProductPo();
                inoutOrderProductPo.setRsId("111111");
                inoutOrderProductPo.setSupplierName("添加商品时统一入库");
                inoutOrderProductPo.setPrice(tmpProductSpecValuePo.getCostPrice());
                inoutOrderProductPo.setProdCount(tmpProductSpecValuePo.getStock());
                BigDecimal price = new BigDecimal(Double.parseDouble(inoutOrderProductPo.getPrice()));
                price = price.multiply(new BigDecimal(Double.parseDouble(inoutOrderProductPo.getProdCount()))).setScale(2, BigDecimal.ROUND_HALF_EVEN);
                inoutOrderProductPo.setAmount(price.doubleValue() + "");
                inoutOrderProductPo.setItemId(GenerateCodeFactory.getGeneratorId("11"));
                inoutOrderProductPo.setOrderId(inoutOrderPo.getOrderId());
                inoutOrderProductPo.setProductId(productPo.getProductId());
                inoutOrderProductPo.setProdName(productPo.getProdName());
                inoutOrderProductPo.setShopId(inoutOrderPo.getShopId());
                inoutOrderProductPo.setState(InoutOrderDto.STATE_W);
                inoutOrderProductPo.setValueId(tmpProductSpecValuePo.getValueId());
                inoutOrderProductPo.setRemark("添加商品时统一入库");
                inoutOrderProductPo.setSpecName(tmpProductSpecValuePo.getSpecName());
                inoutOrderProductPos.add(inoutOrderProductPo);
            }
        }
        flag = iInoutOrderProductInnerServiceSMOImpl.saveInoutOrderProducts(inoutOrderProductPos);
        if (flag < 1) {
            throw new IllegalArgumentException("提交失败");
        }
        flag = inoutOrderInnerServiceSMOImpl.saveInoutOrder(inoutOrderPo);
        if (flag < 1) {
            throw new IllegalArgumentException("提交失败");
        }


    }


    /**
     * 保存关键词
     *
     * @param productPo
     */
    private void doSavakeywords(ProductPo productPo) {
        String[] keywor = productPo.getKeyword().replaceAll("；", ";").split(";");
        for (String keyword : keywor) {
            ProductServKeywordPo servKeywordPo = new ProductServKeywordPo();
            servKeywordPo.setKeywordId(GenerateCodeFactory.getGeneratorId("11"));
            servKeywordPo.setKeywordName(keyword.trim());
            servKeywordPo.setKeywordType(HousekeepingServDto.KEYWORD_PROD_TYPE_CD);
            servKeywordPo.setObjId(productPo.getProductId());
            servKeywordPo.setShopId(productPo.getShopId());
            int save = productServKeywordInnerServiceSMOImpl.saveProductServKeyword(servKeywordPo);
            if (save < 1) {
                throw new IllegalArgumentException("商品关键字保存失败");
            }
        }
    }


}
